<?php
/**
 * Created by PhpStorm.
 * User: 11893
 * Date: 2018/11/14
 * Time: 17:10
 */

namespace Mars\PageCache\Middleware;

use Mars\PageCache\Cache;
use Mars\PageCache\CacheInterface;
use Symfony\Component\HttpFoundation\Request;
use Closure;
use Symfony\Component\HttpFoundation\Response;

class PageCacheMiddleware
{
    protected $cache;

    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    public function handle(Request $request, Closure $next)
    {
        if ($this->cache->shouldCache($request)) {
            $response = $next($request);
            $this->cache->cache($request, $response);
        } else {
            $response = Response::create($this->cache->output($request));
        }
        return $response;
    }

}